package com.example.kotlinlearningproject.network

import android.content.Context
import android.media.MediaPlayer
import android.util.Log
import com.example.kotlinlearningproject.utils.Const
import okhttp3.Call
import okhttp3.Callback
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.io.InputStream

private const val TAG = "DownloadHandler"

class DownloadHandler(context: Context) {

    private var mContext: Context = context
    private var okHttpClient: OkHttpClient = OkHttpClient()
    private val fileName = "xxx.mp3"

    fun downloadAudio(path: String) {
        val request = Request.Builder()
            .url(path)
            .build()
        okHttpClient.newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                Log.e(TAG, "Download audio failed")
            }

            override fun onResponse(call: Call, response: Response) {
                writeToSDCard(response)
                playAudio()
            }
        })
    }

    private fun writeToSDCard(response: Response) {
        // val savePath = Environment.getExternalStorageDirectory().absolutePath + File.separator + APP_FOLDER
        val savePath = mContext.getExternalFilesDir(null).toString() + File.separator + Const.APP_FOLDER
        val dir = File(savePath)
        if (!dir.exists()) {
            dir.mkdirs()
        }
        val file = File(dir, fileName)
        val fileOutputStream: FileOutputStream?
        val fileReader = ByteArray(4096)
        val fileSize = response.body!!.contentLength()
        var sum: Long = 0
        val inputStream: InputStream? = response.body?.byteStream()
        fileOutputStream = FileOutputStream(file)
        var read: Int
        while (inputStream?.read(fileReader).also { read = it!! } != -1) {
            fileOutputStream.write(fileReader, 0, read)
            sum += read.toLong()
            val progress = (sum * 1.0 / fileSize * 100).toInt()
            Log.e(TAG,"downloaded $sum of $fileSize, progress: $progress")
        }
        fileOutputStream.flush()
        Log.e(TAG, "Download audio completed")
        inputStream?.close()
        fileOutputStream.close()
    }

    private fun playAudio() {
        val mediaPlayer = MediaPlayer()
        mediaPlayer.setDataSource(mContext.getExternalFilesDir(null).toString()
                + File.separator + Const.APP_FOLDER + fileName)
        // 同步准备并播放
        mediaPlayer.prepare()
        Log.d(TAG, "prepare完成**********")
        mediaPlayer.start()
    }
}